﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Persistencia;



namespace PersistenciaImplementacion
{
    public abstract class Broker
    {
        public abstract String GetSQLCreate();
        public abstract String GetSQLDelete();
        public abstract String GetSQLUpdate();
        public abstract String GetSQLSelect();
        public abstract ObjetoPersistible ReaderToObject(DbDataReader reader);
        public abstract void LoadReferences(SqlCommand comando, ObjetoPersistible obj);
        public abstract void LoadReferencesWhere(SqlCommand comando, ObjetoPersistible obj);
        public abstract String InsertarHijos(Object objeto, ObjetoPersistible obj);
        public static SqlConnection con = Conexion.GetInstance().ConectarBase();

        public void Create(ObjetoPersistible obj) 
        {
            String query = GetSQLCreate();
            SqlCommand cmd = new SqlCommand(query, con);
            LoadReferences(cmd, obj);
            con.Open();
            object o = cmd.ExecuteScalar();
            String queryHijos = InsertarHijos(o, obj);
            if (queryHijos != null) 
            {
                SqlCommand cmdHijos = new SqlCommand(queryHijos, con);
                cmdHijos.ExecuteNonQuery();
            }
            con.Close();
        }
        
        public void Delete(ObjetoPersistible obj) 
        {
            String query = GetSQLDelete();
            SqlCommand cmd = new SqlCommand(query, con);
            LoadReferencesWhere(cmd, obj);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }

        public void Update(ObjetoPersistible obj) 
        {
            String query = GetSQLUpdate();
            SqlCommand cmd = new SqlCommand(query, con);
            LoadReferencesWhere(cmd, obj);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }

        public List<ObjetoPersistible> Select(ObjetoPersistible obj) 
        {
            String query = GetSQLSelect();
            SqlCommand cmd = new SqlCommand(query, con);
            //LoadReferencesWhere(cmd, obj);
            con.Open();
            DbDataReader reader = cmd.ExecuteReader();
            List<ObjetoPersistible> lista = new List<ObjetoPersistible>();
            while (reader.Read())
            {
                lista.Add(ReaderToObject(reader));
            }
            con.Close();
            return lista;            
        }
    }
}
